package com.jg.visitor.common.utils;

import com.jg.visitor.GlobalConst;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class JwtUtils {

    //token过期时间3天，超过3天后过期，返回401
    public static final long EXPIRE = 1000L * 60 * 60 * 24 * 3;
    //秘钥
    public static final String APP_SECRET = "b02f82421527571113cd628053dbaf0a";


    //进入小程序后默认给一个token，visitor_token
    public static String getTokenByOpenId(String openId){
        return Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setHeaderParam("alg", "HS256")
                .setSubject("visit")
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE))
                //设置token主体部分 ，存储用户信息
                .claim("openId",openId)
                .signWith(SignatureAlgorithm.HS256, APP_SECRET)
                .compact();
    }

    /**
     * 根据visitor_token字符串获取openId
     */
    public static String getOpenIdByJwtTokenAndCheckToken(String visitorToken) {
        if(StringUtils.isEmpty(visitorToken)){
            return null;
        }

        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(visitorToken);

        Claims claims = claimsJws.getBody();

        return (String)claims.get("openId");
    }

    /**
     * 根据snakeToken获取后台人员token
     */
    public static String getTokenBySnakeToken(String snakeToken) {
        Map<String, Object> claims = new HashMap<>();
        claims.put(GlobalConst.LOGIN_USER_KEY, snakeToken);

        return Jwts.builder()
                .setClaims(claims)
                .signWith(SignatureAlgorithm.HS512, APP_SECRET)
                .compact();
    }

    /**
     * 根据后台人员token获取snakeToken
     */
    public static String getSnakeTokenByToken(String adminToken) {
        Claims body = Jwts.parser()
                .setSigningKey(APP_SECRET)
                .parseClaimsJws(adminToken)
                .getBody();

        return  (String) body.get(GlobalConst.LOGIN_USER_KEY);
    }
}
